<?php

class Application_Model_MailTemplateMapper
{
    protected $_dbTable;

    public function setDbTable($dbTable)
    {
        if (is_string($dbTable)) {
            $dbTable = new $dbTable();
        }
        if (!$dbTable instanceof Zend_Db_Table_Abstract) {
            throw new Exception('Invalid table data gateway provided');
        }
        $this->_dbTable = $dbTable;
        return $this;
    }

    public function getDbTable()
    {
        if (null === $this->_dbTable) {
            $this->setDbTable('Application_Model_DbTable_MailTemplate');
        }
        return $this->_dbTable;
    }

    public function findByCode($key, Application_Model_MailTemplate $tpl)
    {

        $language = Zend_Registry::get('language');
        $db       = Zend_Registry::get('db');

        if ($db && $language->getId() > 0) {
            $select = $db->select()->from(array('t' => 'mail_template'));
            $select->join(array('tl' => 'mail_template_local'), 'tl.template_id = t.id');
            $select->where('t.code = ?',          $key);
            $select->where('tl.language_id = ?', $language->getId());
            $stmt = $db->query($select);
            $result = $stmt->fetch();

            if (!empty($result) && is_array($result)) {
                if (!empty($result['id'])) {
                    $tpl->setId($result['id']);
                }
                if (!empty($result['code'])) {
                    $tpl->setCode($result['code']);
                }
                if (!empty($result['from_email'])) {
                    $tpl->setFromEmail($result['from_email']);
                }
                if (!empty($result['allow_use'])) {
                    $tpl->setAllowUse($result['allow_use']);
                }
                if (!empty($result['allow_edit'])) {
                    $tpl->setAllowEdit($result['allow_edit']);
                }
                if (!empty($result['allow_delete'])) {
                    $tpl->setAllowDelete($result['allow_delete']);
                }
                if (!empty($result['tokens'])) {
                    $tpl->setTokens($result['tokens']);
                }
                if (!empty($result['subject'])) {
                    $tpl->setSubject($result['subject']);
                }
                if (!empty($result['from_name'])) {
                    $tpl->setFromName($result['from_name']);
                }
                if (!empty($result['content'])) {
                    $tpl->setContent($result['content']);
                }
            }
        }

        return $tpl;
    }
}